<script setup lang='ts' name="send-goods">
import type { FormRules } from 'element-plus'

import { useJcOrderMetaGetOne, useShipOrder } from '@fl/api/supplier'
import { SearchTable } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { cloneDeep } from 'lodash-es'
import NP from 'number-precision'

const visible = defineModel<boolean>('visible')
const id = defineModel('id')

const { data, isLoading } = useJcOrderMetaGetOne(id)

const { isPending, mutate } = useShipOrder()

const state = { attachmentUrl: [], estimatedShippingDate: '', logisticsCompany: '', shippingInstructions: '', trackingNumber: '' }

const form = ref<any>({ ...state })

const formRef = ref()

const tableRef = ref<any>()

const dataList = ref<any>([])

const gridOptions = reactive<any>({
    align: 'center',
    border: true,
    columns: [
        { field: 'brand', title: '品牌' },
        { field: 'model', title: '型号' },
        { field: 'unit', title: '单位' },
        { field: 'quantity', title: '数量' },
        { field: 'deliverAccumulativeTotal', title: '累计发货数量' },
        { field: 'acceptAccumulativeTotal', title: '累计验收数量' },
        { slots: { default: 'remaining' }, title: '剩余应发数量' },
        { headerClassName: 'redStar', slots: { default: 'count' }, title: '本次发货数量' },
    ],
    data: [],
    height: 350,
    showOverflow: true,
})
const rules = reactive<FormRules<any>>({
    attachmentUrl: [
        { message: '请上传发货单附件', required: true, trigger: 'blur' },
    ],
    estimatedShippingDate: [
        { message: '请选择预计发货时间', required: true, trigger: 'blur' },
    ],
    logisticsCompany: [
        { message: '请输入物流公司', required: true, trigger: 'blur' },
    ],
    shippingInstructions: [
        { message: '请输入发货说明', required: true, trigger: 'blur' },
    ],
    trackingNumber: [
        { message: '请输入物流单号', required: true, trigger: 'blur' },
    ],
})

async function submit() {
    const valid = await formRef.value.validate()
    if (valid) {
        const attachmentUrl = form.value.attachmentUrl.map((item: any) => item.url)

        const params = {
            ...form.value,
            attachmentUrl: JSON.stringify(attachmentUrl),
            orderId: id.value,
            orderNo: data.value.orderNo,
            products: dataList.value,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
}

watchEffect(() => {
    if (data.value) {
        dataList.value = cloneDeep(data.value?.orderProductsVOS ?? [])
        dataList.value.forEach(item => item.quantityShipped = 1)
    }
})
</script>

<template>
    <el-dialog v-model="visible"
               width="1200"
               :close-on-click-modal="false"
               title="发货单"
               @close="cancel"
               @closed="reset"
    >
        <el-skeleton v-if="isLoading"
                     :rows="5"
        />

        <template v-else>
            <div class="info-title">
                收货信息
            </div>

            <el-form ref="formRef"
                     :model="form"
                     :rules="rules"
                     label-width="auto"
            >
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="预计发货时间"
                                      prop="estimatedShippingDate"
                        >
                            <el-date-picker v-model="form.estimatedShippingDate"
                                            type="date"
                                            placeholder="请选择预计发货时间"
                                            value-format="YYYY-MM-DD"
                                            class="w-full"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="发货说明"
                                      prop="shippingInstructions"
                        >
                            <el-input v-model="form.shippingInstructions" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="物流公司"
                                      prop="logisticsCompany"
                        >
                            <el-input v-model="form.logisticsCompany" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="物流单号"
                                      prop="trackingNumber"
                        >
                            <el-input v-model="form.trackingNumber" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="发货单附件"
                                      prop="attachmentUrl"
                        >
                            <FlUpload v-model="form.attachmentUrl"
                                      :limit="10"
                                      list-type="text"
                                      accept=".png,.jpg,.jpeg,.docx,.xlsx,.pdf"
                                      tips
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div class="info-title">
                商品信息
            </div>

            <SearchTable v-bind="gridOptions"
                         ref="tableRef"
                         :data="dataList"
            >
                <template #remaining="{ row }">
                    {{ NP.round(row.quantity - row.acceptAccumulativeTotal, 0) }}
                </template>

                <template #count="{ row }">
                    <el-input-number v-model="row.quantityShipped"
                                     style="width: 100px;"
                                     :precision="0"
                                     :min="1"
                                     :max="NP.round(row.quantity - row.acceptAccumulativeTotal, 0)"
                                     size="small"
                    />
                </template>
            </SearchTable>

            <div style="text-align: center;margin-top: 10px;">
                <el-button @click="cancel">
                    关闭
                </el-button>

                <el-button type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    确认发货
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="less" scoped>
:deep(.redStar) {
    span::before {
        content: '*';
        color: red;
        margin-right: 2px;
    }
}

.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 40px;
}
</style>
